package com.syp.test.clustercacheflush.util.zkflushcache;

import java.io.UnsupportedEncodingException;

import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syp.test.clustercacheflush.util.Constants;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ZkCacheSerializer implements ZkSerializer {

	@Override
	public byte[] serialize(Object data) throws ZkMarshallingError {
		if (data != null) {
			String json = JSON.toJSONString(data);
			try {
				return json.getBytes(Constants.CHARSET_UTF8);
			} catch (UnsupportedEncodingException e) {
				log.error("str encoding error.", e);
			}
		}
		return null;
	}

	@Override
	public Object deserialize(byte[] bytes) throws ZkMarshallingError {
		if (bytes != null) {
			try {
				String jsonString = new String(bytes, Constants.CHARSET_UTF8);
				JSONObject json = JSON.parseObject(jsonString);
				ZkCacheSyncNotify notify = JSON.toJavaObject(json, ZkCacheSyncNotify.class);
				return notify;
			} catch (UnsupportedEncodingException e) {
				log.error("str encoding error.", e);
			}
		}
		return null;
	}

}
